package com.android.play;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2016/8/28.
 */

public class ImageAdapter extends BaseAdapter {

    private final String TAG="ImageAdapter";

    private List<String> imageUrls;

    private List<String> imageUrlLocal;

    private Context context;

    private ImageAdapter adapter;

    private ImageView imageView;

    public static Integer[] imgs = {

    };

    public ImageAdapter(Context context){
        this.context=context;
    }

    public ImageAdapter(List<String> list,Context context){
        this.imageUrls=list;
        this.context=context;
        this.adapter=this;
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public Object getItem(int i) {
        return imageUrls.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View contentView, ViewGroup viewGroup) {
        Bitmap image = null;
        imageUrlLocal = getImagePathFromSD();
        if (contentView==null){
            contentView= LayoutInflater.from(context).inflate(R.layout.item,null);
            //控制图片的显示大小 不加这一句会变成多张图片显示
            Gallery.LayoutParams params = new Gallery.LayoutParams(Gallery.LayoutParams.WRAP_CONTENT,Gallery.LayoutParams.WRAP_CONTENT);
            contentView.setLayoutParams(params);
            Log.i(TAG, "getView: --->"+imageUrlLocal.size());
            if (imageUrls==null){
                image = BitmapFactory.decodeFile(imageUrlLocal.get(position % imageUrlLocal.size()));
                if(image==null){
                    imageView.setImageResource(R.mipmap.img_1);
                }
            }else {
                //从缓存中获取图片
                image = ((MainActivity)context).imagesCache.get(imageUrls.get(position % imageUrls.size()));
                if (image == null){
                    //当缓存中没有要使用的图片时，先显示默认的图片
                    image = ((MainActivity)context).imagesCache.get("load");
                    //开始异步加载
                    LoadImageTask imageTask=new LoadImageTask(contentView);
                    imageTask.execute(imageUrls.get(position % imageUrls.size()));
                    contentView.setTag(image);
                }
            }

        }else {
            image= (Bitmap) contentView.getTag();
        }
        //设置缩放比例：保持原样
        imageView= (ImageView) contentView.findViewById(R.id.slid_iamge);
        if (image != null) {
            imageView.setImageBitmap(image);
        }else{

            imageView.setImageResource(R.mipmap.img_1);
        }
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        return contentView;
    }

    @SuppressWarnings("unused")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case 0: {
                        adapter.notifyDataSetChanged();
                    }
                    break;
                }

                super.handleMessage(msg);
            } catch (Exception e) {
            }
        }
    };

    //加载图片的异步任务
    class LoadImageTask extends AsyncTask<String,Void,Bitmap>{
        private View resultView;

        LoadImageTask(View resultView) {
            this.resultView = resultView;
        }
        // doInBackground完成后才会被调用
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            //调用setTag保存图片以便于自动更新图片
            resultView.setTag(bitmap);
        }
        //从网上下载图片
        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap image=null;
            try {
                //new URL对象  把网址传入
                URL url = new URL(params[0]);
                //取得链接
                URLConnection conn = url.openConnection();
                conn.connect();
                //取得返回的InputStream
                InputStream is = conn.getInputStream();
                //将InputStream变为Bitmap
                image = BitmapFactory.decodeStream(is);
                is.close();
                ((MainActivity)context).imagesCache.put(params[0],image);   //把下载好的图片保存到缓存中
                Message m = new Message();
                m.what = 0;
                mHandler.sendMessage(m);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return image;
        }
    }

    /**
     * 从sd卡获取图片资源
     *
     * @return
     */
    private List<String> getImagePathFromSD() {
        // 图片列表
        List<String> imagePathList = new ArrayList<String>();
        // 得到sd卡内image文件夹的路径File.separator()
        String path= Environment.getExternalStorageDirectory().toString() + File.separator+ "image";
        File picFile = new File(path);
        File[] listPicFiles = picFile.listFiles();
        for (File file2 : listPicFiles) {
            imagePathList.add(file2.getAbsolutePath());
        }
        if (imagePathList.size()==0) {
            return null;
        }
        return imagePathList;
    }

}
